//
//  LPFComposeVC.swift
//  WeiBo
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD

class LPFComposeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(composePictureView)
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENH - 20))
            make.leading.equalTo(10)
            make.top.equalTo(composeTextView).offset(100)
        }
        
        // MARK: - 监听toolbar 按钮点击
        composeToolBar.composeToolBarColsure = {[weak self](type: LPFComposeToolBarType) in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyborad()
            case .Add:
                print("+")
            }
        }
        // MARK: - 监听弹出图片控制器
        composePictureView.ComposePictureViewClosure = {[weak self] in
            self?.selectImage()
        }
        // MARK: - 通知监听键盘弹出frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // MARK: - 接收通知 删除文本信息
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "clickDeleteButton", name: LPFEmoticonDeleteButtonNotification, object: nil)
        
        // MARK: - 表情键盘表情按钮通知接收
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: LPFEmoticonButtonNSNotification, object: nil)
        
    }
    
    // MARK: - 通知监听键盘弹出frame改变方法
    func keyboardWillChangeFrame(noti: NSNotification){
        // 获取键盘的rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新composeToolBar约束
        composeToolBar.snp_updateConstraints{ (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 接收通知时间  删除文本信息
    func clickDeleteButton(){
        //删除文本信息方法
        composeTextView.deleteBackward()
    }
    
    // MARK: - 监听表情键盘的按钮点击
    func emoticonButtonClick(noti: NSNotification){
        guard let emoticon = noti.object as? LPFEmoticonModel else{
            return
        }
        // 代表是emoji表情
        if emoticon.isEmoji{
            // 把十六进制的字符串转成emoji表情
            let code = ((emoticon.code ?? "") as NSString).emoji()
            // 插入emoji表情
            composeTextView.insertText(code)
        }else{
            // 图片表情
            
            // 得到我们以前的富文本
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //初始化一个image
            let s1 = emoticon.path ?? ""
            let s2 = emoticon.png ?? ""
            let path = "\(s1)\(s2)"
            
            let image = UIImage(named: path, inBundle: LPFEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            // 得到行高
            let lineHeight = composeTextView.font!.lineHeight
            //初始化一个文本附件
            let att = LPFTextAttachment()
            att.emoticon = emoticon
            
            //设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            att.image = image
            // 初始化一个不可变富文本
            let attr = NSAttributedString(attachment: att)
            
            // 添加到textview 用替换选中部分的文本
            // 获取textView 的光标
            let selectedRange = composeTextView.selectedRange
            // 替换选中部分的文本
            oldAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
            // 设置富文本字体
            oldAttr.addAttribute(NSFontAttributeName, value: composeTextView.font!, range: NSMakeRange(0, oldAttr.length))
            //显示
            composeTextView.attributedText = oldAttr
            //光标位置
            composeTextView.selectedRange = NSMakeRange(selectedRange.location + 1, 0)
            
            //发送通知 隐藏站位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //改变右侧发送按钮的状态
//            textViewDidChange(composeTextView)  //方法一
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
    }
    
    // MARK: - 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 设置导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    // MARK: - 导航栏点击方法  返回
    @objc private func cancel(){
        //取消composeTextView的第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: - 导航栏点击方法  发送
    @objc private func send(){
        
        // 创建一个可变字符串保存我们遍历的到的字符串
        var result: String = String()
        // 遍历attributedText 得对每次遍历到的对象 和对应的位置
        composeTextView.attributedText.enumerateAttributesInRange(NSMakeRange(0, composeTextView.attributedText.length), options: []) { (dictInfo, range, _) -> Void in
            if let att = dictInfo["NSAttachment"] as? LPFTextAttachment{
                result += att.emoticon?.chs ?? ""
            }else{
                // 从我们的富文本中 截取出里面的文字
                let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                result += name
            }
        }
        

        
        // 如果配图数据的count 不等于0 就代表是会发布图片微博
        if composePictureView.images.count != 0{
            upload(result)
        }else{
            update(result)
        }
        
    }
    
    // MARK: - titleView
    private lazy var titleView: UILabel = {
        let name = LPFUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        let titleString = "发微博\n\(name)"
        //副文本
        let attr = NSMutableAttributedString(string: titleString)
        // 获取range
        let range = (titleString as NSString).rangeOfString(name)
        //设置指定位置的颜色 和字体大小
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
        label.attributedText = attr
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        return label
    }()
    
    // MARK: - 文本输入框
    private lazy var composeTextView: LPFComposeTextView = {
        let view = LPFComposeTextView()
        view.font = UIFont.systemFontOfSize(16)
        view.delegate = self
        view.placeholder = "我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言"
        //总是竖直滑动
        view.alwaysBounceVertical = true
        return view
    }()
    // MARK: - 底部toolbar
    private lazy var composeToolBar: LPFComposeToolBar = LPFComposeToolBar()
    // MARK: - 配图
    private lazy var composePictureView: LPFComposePictureView = LPFComposePictureView()
    // MARK: - 自定义表情键盘
    private lazy var emoticonKeyboard:LPFEmoticonKeyboardView = {
        let view = LPFEmoticonKeyboardView()
        view.frame = CGRect(x: 0, y: 0, width: SCREENH, height: 216)
        
        return view
    }()
}
// MARK: - UITextViewDelegate
extension LPFComposeVC: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //滚动时 取消第一响应者状态 这里指键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

// MARK: - 处理toolbar 里面的按钮点击事件
extension LPFComposeVC{
    // 选择image
    func selectImage(){
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            
        }else{
            //不能打开相机
            presentViewController(pickerVC, animated: true, completion: nil)
        }
    }
    
    // 切换键盘
    func switchKeyborad(){
        if composeTextView.inputView == nil{
            //表情键盘
            composeTextView.inputView = emoticonKeyboard
            composeToolBar.isEmoticon = true
        }else{
            //系统键盘
            composeTextView.inputView = nil
            composeToolBar.isEmoticon = false
        }
        
        // 刷新InputViews
        composeTextView.reloadInputViews()
        // 当我们点击该按钮的时候叫键盘弹出 需要成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}

// MARK: - UIImagePickerControllerDelegate
extension LPFComposeVC: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    // 用户选择图片后回调方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        composePictureView.addImage(getImageScale(image, width: 600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
        // 如果我们的图片宽度小于我们制定的宽度我们直接返回 不处理
        if image.size.width < width{
            return image
        }
        let height = (image.size.height * width) / image.size.width
        
        // 开启上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        // 把image渲染到上下文中
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        // 得到结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return result
    }
}

// MARK: - 发布微博
extension LPFComposeVC{
    //文字微博
    func update(status: String){
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //请求参数
        let params = [
            "access_token": LPFUserAccountTools.sharedTools.accessToken!,
            "status": status
        ]
        
        LPFNetworkTools.sharedTools.request(LPFRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    // 发布一条文字和图片微博
    func upload(status: String){
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        //请求参数
        let params = [
            "access_token": LPFUserAccountTools.sharedTools.accessToken!,
            "status": status
        ]
        
        LPFNetworkTools.sharedTools.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            //上传多张图片
            for i in self.composePictureView.images{
                // 通过image 得到二进制数据
                let data = UIImagePNGRepresentation(i)!
                // 使用表单形式发送图片
                formdata.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "image/jpeg")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }) { (_, error) -> Void in
                SVProgressHUD.showSuccessWithStatus("发送失败")
        }

    }
}
